package com.gitee.hermer.engine.jars.demo.boot;

import java.util.logging.Logger;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import com.gitee.hermer.boot.jee.commons.collection.CollectionUtils;
import com.gitee.hermer.boot.jee.commons.log.Logger.Level;
import com.gitee.hermer.boot.jee.commons.log.UtilsContext;
import com.gitee.hermer.boot.jee.commons.utils.StringUtils;

@MapperScan({"com.topisv.wms.**.dao"})
@Import({MysqlDBConfig.class})
@Configuration
public class MyBatisConfig{

	private com.gitee.hermer.boot.jee.commons.log.Logger LOGGER = com.gitee.hermer.boot.jee.commons.log.Logger.getLogger(MyBatisConfig.class);

	@Bean
	public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
		try{
			SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
			LOGGER.info(StringUtils.format("SqlSessionFactory start:{}",dataSource.toString()));
			bean.setDataSource(dataSource);
			Resource configLocation = new org.springframework.core.io.ClassPathResource("mybatis-config.xml");
			PathMatchingResourcePatternResolver s = new PathMatchingResourcePatternResolver();
			bean.setConfigLocation(configLocation);
			Resource[] resources = s.getResources("classpath*:/com/topisv/wms/mapper/**/*.xml");
			if(CollectionUtils.isNotEmpty(resources)){
				if(LOGGER.isEnabled(Level.Debug)){
					LOGGER.debug(StringUtils.format("find mybatis mappers -> [{}]",CollectionUtils.newArrayList(resources).toString()));
				}
			}
			bean.setMapperLocations(resources);
			LOGGER.info("SqlSessionFactory finished");
			SqlSessionFactory factory=null;
			try
			{
				factory=bean.getObject();
			}catch(Throwable e)
			{
				LOGGER.error("mybatis xml load error",e);
			}
			return factory;
		}catch (Exception e) {
			LOGGER.error(e.getMessage(),e);
			throw new IllegalStateException(e.getMessage(), e);
		}
	}


}
